<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>管理员后台</title>
    <link rel="icon" href="./images/gongzhenglogo.png">
    <link rel="stylesheet" href="./bootstrap-5.3.0-alpha1-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --accent-color: #4895ef;
            --success-color: #4cc9f0;
            --danger-color: #f72585;
            --dark-color: #242a38;
            --light-color: #f8f9fa;
        }
        
        body {
            background: linear-gradient(135deg, #f6f8ff 0%, #f0f4ff 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: #333;
            min-height: 100vh;
        }
        
        .admin-container {
            max-width: 1100px;
            margin: 30px auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
        
        .admin-sidebar {
            background: var(--dark-color);
            color: white;
            padding: 25px 0;
            height: 100%;
            min-height: 600px;
        }
        
        .admin-logo {
            text-align: center;
            padding: 15px 0 30px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 20px;
        }
        
        .admin-logo h3 {
            font-size: 1.5rem;
            font-weight: 700;
            margin: 0;
            color: white;
        }
        
        .admin-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .admin-menu li {
            padding: 12px 25px;
            cursor: pointer;
            transition: all 0.3s;
            border-left: 4px solid transparent;
        }
        
        .admin-menu li:hover, .admin-menu li.active {
            background: rgba(255, 255, 255, 0.1);
            border-left-color: var(--accent-color);
        }
        
        .admin-menu li i {
            margin-right: 10px;
            font-size: 1.1rem;
        }
        
        .admin-content {
            padding: 30px;
        }
        
        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .content-header h2 {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--dark-color);
            margin: 0;
        }
        
        .section-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
            padding: 25px;
            margin-bottom: 30px;
            transition: transform 0.3s, box-shadow 0.3s;
        }
        
        .section-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        }
        
        .section-title {
            font-size: 1.4rem;
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 20px;
            display: flex;
            align-items: center;
        }
        
        .section-title i {
            margin-right: 10px;
            color: var(--primary-color);
            font-size: 1.5rem;
        }
        
        .form-switch {
            padding-left: 3em;
        }
        
        .form-check-input {
            width: 3em;
            height: 1.5em;
            cursor: pointer;
        }
        
        .form-check-input:checked {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .switch-label {
            font-size: 1.1rem;
            margin-left: 15px;
            font-weight: 500;
        }
        
        .user-table {
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
        }
        
        .user-table th {
            background: var(--primary-color);
            color: white;
            font-weight: 600;
            text-align: center;
            padding: 15px;
            font-size: 1.05rem;
        }
        
        .user-table td {
            padding: 15px;
            text-align: center;
            vertical-align: middle;
        }
        
        .user-table tbody tr {
            transition: background 0.2s;
        }
        
        .user-table tbody tr:hover {
            background: #f8f9ff;
        }
        
        .btn-danger {
            background: var(--danger-color);
            border: none;
            padding: 6px 15px;
            border-radius: 6px;
        }
        
        .btn-danger:hover {
            background: #d61a6c;
        }
        
        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 500;
            font-size: 0.9rem;
            display: inline-block;
        }
        
        .status-on {
            background: rgba(76, 201, 240, 0.15);
            color: var(--success-color);
        }
        
        .status-off {
            background: rgba(247, 37, 133, 0.15);
            color: var(--danger-color);
        }
        
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #eee;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
            font-weight: bold;
            color: var(--dark-color);
        }
        
        .role-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .role-admin {
            background: rgba(67, 97, 238, 0.15);
            color: var(--primary-color);
        }
        
        .role-user {
            background: rgba(76, 201, 240, 0.15);
            color: var(--success-color);
        }
        
        /* 内容区域显示控制 */
        .content-section {
            display: none;
        }
        
        .content-section.active {
            display: block;
        }
        
        /* 加载动画 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: var(--primary-color);
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 操作按钮 */
        .action-btn {
            margin-top: 15px;
            margin-right: 10px;
        }
        
        /* 消息提示 */
        .message-box {
            padding: 10px 15px;
            border-radius: 8px;
            margin-top: 15px;
            display: none;
        }
        
        .message-success {
            background-color: rgba(76, 201, 240, 0.15);
            color: var(--success-color);
            border: 1px solid rgba(76, 201, 240, 0.3);
        }
        
        .message-error {
            background-color: rgba(247, 37, 133, 0.15);
            color: var(--danger-color);
            border: 1px solid rgba(247, 37, 133, 0.3);
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <div class="row g-0">
            <!-- 侧边栏 -->
            <div class="col-md-3 admin-sidebar">
                <div class="admin-logo">
                    <h3>执剑管理系统</h3>
                </div>
                <ul class="admin-menu">
                    <li data-section="dashboard" class="active"><i class="bi bi-speedometer2"></i> 控制面板</li>
                    <li data-section="users"><i class="bi bi-people"></i> 用户管理</li>
                    <li data-section="orders"><i class="bi bi-cart3"></i> 订单管理</li>
                    <li data-section="settings"><i class="bi bi-gear"></i> 系统设置</li>
                    <li id="logoutBtn"><i class="bi bi-box-arrow-right"></i> 退出系统</li>
                </ul>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-9 admin-content">
                <div class="content-header">
                    <h2 id="contentTitle">控制面板</h2>
                    <div class="user-info">
                        <span>管理员，您好！</span>
                    </div>
                </div>
                
                <!-- 控制面板内容 -->
                <div id="dashboard" class="content-section active">
                    <!-- 拍卖功能开关 -->
                    <div class="section-card">
                        <div class="section-title">
                            <i class="bi bi-toggle-on"></i> 拍卖功能开关
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="auctionSwitch">
                            <label class="form-check-label switch-label" for="auctionSwitch">
                                <span id="auctionStatusLabel" class="status-badge status-off">拍卖已关闭</span>
                            </label>
                        </div>
                        <div class="mt-3">
                            <button id="clearChatBtn" class="btn btn-warning action-btn">
                                <i class="bi bi-trash"></i> 清除所有聊天记录
                            </button>
                            <button id="checkStatusBtn" class="btn btn-info action-btn">
                                <i class="bi bi-question-circle"></i> 检查服务状态
                            </button>
                        </div>
                        <div id="messageBox" class="message-box"></div>
                    </div>
                </div>
                
                <!-- 用户管理内容 -->
                <div id="users" class="content-section">
                    <div class="section-card">
                        <div class="section-title">
                            <i class="bi bi-people-fill"></i> 用户管理
                        </div>
                        <div id="usersLoading" class="text-center mb-3">
                            <span class="loading"></span> 正在加载用户数据...
                        </div>
                        <table class="table user-table">
                            <thead>
                                <tr>
                                    <th>用户ID</th>
                                    <th>用户名</th>
                                    <th>邮箱</th>
                                    <th>角色</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="userList">
                                <!-- 用户数据将通过JS动态填充 -->
                            </tbody>
                        </table>
                        <div id="userPagination" class="mt-3"></div>
                    </div>
                </div>
                
                <!-- 订单管理内容 -->
                <div id="orders" class="content-section">
                    <div class="section-card">
                        <div class="section-title">
                            <i class="bi bi-cart-fill"></i> 订单管理
                        </div>
                        <div id="ordersLoading" class="text-center mb-3">
                            <span class="loading"></span> 正在加载订单数据...
                        </div>
                        <table class="table user-table">
                            <thead>
                                <tr>
                                    <th>订单号</th>
                                    <th>订单类型</th>
                                    <th>商品名称</th>
                                    <th>下单时间</th>
                                    <th>金额</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="orderList">
                                <!-- 订单数据将通过JS动态填充 -->
                            </tbody>
                        </table>
                        <div id="orderPagination" class="mt-3"></div>
                    </div>
                </div>
                
                <!-- 系统设置内容 -->
                <div id="settings" class="content-section">
                    <div class="section-card">
                        <div class="section-title">
                            <i class="bi bi-gear-fill"></i> 系统设置
                        </div>
                        <div class="mb-3">
                            <label for="systemName" class="form-label">系统名称</label>
                            <input type="text" class="form-control" id="systemName" value="执剑管理系统">
                        </div>
                        <div class="mb-3">
                            <label for="adminEmail" class="form-label">管理员邮箱</label>
                            <input type="email" class="form-control" id="adminEmail" value="admin@example.com">
                        </div>
                        <button class="btn btn-primary" id="saveSettings">保存设置</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 验证用户是否已登录
        function checkLogin() {
            const secretKey = sessionStorage.getItem('secretKey');
            if (!secretKey) {
                // 未登录，跳转到登录页
                window.location.href = 'login.html';
                return false;
            }
            
            // 验证秘钥是否有效
            fetch(`http://localhost:8080/api/secret-keys/byKeyValue?keyValue=${encodeURIComponent(secretKey)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('秘钥验证失败');
                    }
                    return response.json();
                })
                .catch(error => {
                    console.error('秘钥验证失败:', error);
                    // 秘钥无效，清除存储并跳转到登录页
                    sessionStorage.removeItem('secretKey');
                    window.location.href = 'login.html';
                });
            
            return true;
        }
        
        // 拍卖功能开关逻辑
        const auctionSwitch = document.getElementById('auctionSwitch');
        const auctionStatusLabel = document.getElementById('auctionStatusLabel');
        const messageBox = document.getElementById('messageBox');
        const clearChatBtn = document.getElementById('clearChatBtn');
        const checkStatusBtn = document.getElementById('checkStatusBtn');
        
        // 显示消息
        function showMessage(message, isSuccess = true) {
            messageBox.textContent = message;
            messageBox.className = isSuccess ? 'message-box message-success' : 'message-box message-error';
            messageBox.style.display = 'block';
            
            // 3秒后自动隐藏消息
            setTimeout(() => {
                messageBox.style.display = 'none';
            }, 3000);
        }
        
        // 初始化时获取TCP服务状态
        function checkTcpStatus() {
            const secretKey = sessionStorage.getItem('secretKey');
            
            fetch(`http://localhost:8080/api/tcp/status?secretKey=${encodeURIComponent(secretKey)}`)
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            checkLogin();
                            throw new Error('未授权访问');
                        }
                        throw new Error('获取TCP服务状态失败');
                    }
                    return response.text();
                })
                .then(data => {
                    const isRunning = data === "TCP服务正在运行";
                    auctionSwitch.checked = isRunning;
                    updateAuctionStatus();
                })
                .catch(error => {
                    console.error('获取TCP服务状态失败:', error);
                    showMessage('获取TCP服务状态失败，请检查后端服务', false);
                    auctionSwitch.checked = false;
                    updateAuctionStatus();
                });
        }
        
        // 更新拍卖状态UI
        function updateAuctionStatus() {
            if (auctionSwitch.checked) {
                auctionStatusLabel.textContent = '拍卖已开启';
                auctionStatusLabel.className = 'status-badge status-on';
            } else {
                auctionStatusLabel.textContent = '拍卖已关闭';
                auctionStatusLabel.className = 'status-badge status-off';
            }
        }
        
        // 监听拍卖开关变化
        auctionSwitch.addEventListener('change', function() {
            const url = auctionSwitch.checked 
                ? 'http://localhost:8080/api/tcp/start' 
                : 'http://localhost:8080/api/tcp/stop';
            
            fetch(url, { method: 'POST' })
                .then(response => response.text())
                .then(data => {
                    updateAuctionStatus();
                    showMessage(data);
                })
                .catch(error => {
                    console.error('操作TCP服务失败:', error);
                    // 如果失败，回滚UI状态
                    auctionSwitch.checked = !auctionSwitch.checked;
                    updateAuctionStatus();
                    showMessage('操作失败，请检查后端服务', false);
                });
        });
        
        // 清除聊天记录
        clearChatBtn.addEventListener('click', function() {
            if (confirm('确定要清除所有聊天记录吗？此操作不可恢复！')) {
                fetch('http://localhost:8080/api/tcp/clear', { method: 'DELETE' })
                    .then(response => response.text())
                    .then(data => {
                        showMessage(data);
                    })
                    .catch(error => {
                        console.error('清除聊天记录失败:', error);
                        showMessage('清除聊天记录失败，请检查后端服务', false);
                    });
            }
        });
        
        // 检查服务状态
        checkStatusBtn.addEventListener('click', function() {
            fetch('http://localhost:8080/api/tcp/status')
                .then(response => response.text())
                .then(data => {
                    showMessage(data);
                    const isRunning = data === "TCP服务正在运行";
                    auctionSwitch.checked = isRunning;
                    updateAuctionStatus();
                })
                .catch(error => {
                    console.error('获取TCP服务状态失败:', error);
                    showMessage('获取TCP服务状态失败，请检查后端服务', false);
                });
        });
        
        // 用户管理逻辑
        function loadUsers(page = 1, pageSize = 3) {
            document.getElementById('usersLoading').style.display = 'block';
            document.getElementById('userList').innerHTML = '';
            
            const secretKey = sessionStorage.getItem('secretKey');
            
            // 使用公司信息接口获取用户数据
            fetch(`http://localhost:8080/api/companies?page=${page-1}&size=${pageSize}&secretKey=${encodeURIComponent(secretKey)}`)
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            // 未授权，可能是秘钥失效
                            checkLogin();
                            throw new Error('未授权访问');
                        }
                        throw new Error('获取用户数据失败');
                    }
                    return response.json();
                })
                .then(data => {
                    document.getElementById('usersLoading').style.display = 'none';
                    console.log('用户数据:', data); // 调试用，查看返回的数据结构
                    
                    // 处理不同的返回格式
                    let content = data;
                    let totalPages = 1;
                    
                    // 如果返回的是分页对象
                    if (data.content && Array.isArray(data.content)) {
                        content = data.content;
                        totalPages = data.totalPages || Math.ceil(data.totalElements / pageSize) || 1;
                    } else if (Array.isArray(data)) {
                        // 如果返回的是数组，手动计算分页
                        content = data.slice((page-1) * pageSize, page * pageSize);
                        totalPages = Math.ceil(data.length / pageSize);
                    }
                    
                    renderUsers(content);
                    renderUserPagination(totalPages, page);
                })
                .catch(error => {
                    console.error('获取用户数据失败:', error);
                    document.getElementById('usersLoading').style.display = 'none';
                    document.getElementById('userList').innerHTML = '<tr><td colspan="5" class="text-center">加载用户数据失败，请刷新重试</td></tr>';
                    
                    // 如果接口不可用，使用示例数据
                    const demoUsers = [
                        {companyId: "C001", companyName: '张三公司', email: 'zhangsan@example.com', legalPerson: '张三', phone: '13800138001', registrationDate: '2023-01-01'},
                        {companyId: "C002", companyName: '李四企业', email: 'lisi@example.com', legalPerson: '李四', phone: '13900139001', registrationDate: '2023-02-01'},
                        {companyId: "C003", companyName: '王五集团', email: 'wangwu@example.com', legalPerson: '王五', phone: '13700137001', registrationDate: '2023-03-01'}
                    ];
                    
                    // 手动分页示例数据
                    const paginatedDemoUsers = demoUsers.slice((page-1) * pageSize, page * pageSize);
                    renderUsers(paginatedDemoUsers);
                    renderUserPagination(Math.ceil(demoUsers.length / pageSize), page);
                });
        }
        
        // 渲染用户列表
        function renderUsers(users) {
            const userList = document.getElementById('userList');
            userList.innerHTML = '';
            
            if (users.length === 0) {
                userList.innerHTML = '<tr><td colspan="5" class="text-center">暂无用户数据</td></tr>';
                return;
            }
            
            users.forEach(user => {
                const tr = document.createElement('tr');
                // 确保所有字段都有默认值，防止undefined显示在页面上
                const companyId = user.companyId || '未知';
                const companyName = user.companyName || '未知';
                const legalPerson = user.legalPerson || '未知';
                const email = user.email || '未知';
                const firstChar = companyName.charAt(0);
                
                tr.innerHTML = `
                    <td>${companyId}</td>
                    <td>
                        <div class="d-flex align-items-center justify-content-center">
                            <div class="user-avatar">${firstChar}</div>
                            <span class="ms-2">${companyName}</span>
                        </div>
                    </td>
                    <td>${email}</td>
                    <td><span class="role-badge role-user">${legalPerson}</span></td>
                    <td>
                        <button class="btn btn-danger" onclick="deleteUser('${companyId}')">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                        <button class="btn btn-info" onclick="viewUserDetail('${companyId}')">
                            <i class="bi bi-eye"></i> 详情
                        </button>
                    </td>
                `;
                userList.appendChild(tr);
            });
        }
        
        // 渲染用户分页
        function renderUserPagination(totalPages, currentPage) {
            const paginationElement = document.getElementById('userPagination');
            if (!paginationElement) {
                console.error('找不到用户分页容器元素');
                return;
            }
            
            paginationElement.innerHTML = '';
            
            if (totalPages <= 1) {
                return; // 如果只有一页，不显示分页控件
            }
            
            const ul = document.createElement('ul');
            ul.className = 'pagination justify-content-center';
            
            // 上一页按钮
            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
            const prevLink = document.createElement('a');
            prevLink.className = 'page-link';
            prevLink.href = '#';
            prevLink.innerHTML = '&laquo;';
            prevLink.addEventListener('click', (e) => {
                e.preventDefault();
                if (currentPage > 1) loadUsers(currentPage - 1);
            });
            prevLi.appendChild(prevLink);
            ul.appendChild(prevLi);
            
            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                const link = document.createElement('a');
                link.className = 'page-link';
                link.href = '#';
                link.textContent = i;
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    loadUsers(i);
                });
                li.appendChild(link);
                ul.appendChild(li);
            }
            
            // 下一页按钮
            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
            const nextLink = document.createElement('a');
            nextLink.className = 'page-link';
            nextLink.href = '#';
            nextLink.innerHTML = '&raquo;';
            nextLink.addEventListener('click', (e) => {
                e.preventDefault();
                if (currentPage < totalPages) loadUsers(currentPage + 1);
            });
            nextLi.appendChild(nextLink);
            ul.appendChild(nextLi);
            
            paginationElement.appendChild(ul);
            console.log('用户分页已渲染，总页数:', totalPages, '当前页:', currentPage);
        }
        
        // 查看用户详情
        window.viewUserDetail = function(companyId) {
            fetch(`http://localhost:8080/api/companies/${companyId}`)
                .then(response => response.json())
                .then(data => {
                    if (data) {
                        const detailInfo = `
                            公司ID: ${data.companyId}
                            公司名称: ${data.companyName}
                            法人代表: ${data.legalPerson}
                            联系电话: ${data.phone}
                            电子邮箱: ${data.email}
                            注册日期: ${data.registrationDate}
                        `;
                        alert(detailInfo);
                    } else {
                        alert('未找到该公司信息');
                    }
                })
                .catch(error => {
                    console.error('获取公司详情失败:', error);
                    alert('获取公司详情失败，请稍后重试');
                });
        }
        
        // 删除用户
        window.deleteUser = function(companyId) {
            if(confirm('确定要删除该用户吗？')) {
                // 实际应用中应该调用删除接口
                alert(`已发送删除请求，公司ID: ${companyId}`);
                // 重新加载用户列表
                loadUsers();
            }
        }
        
        // 订单管理逻辑
        function loadOrders(page = 1, pageSize = 3) {
            document.getElementById('ordersLoading').style.display = 'block';
            document.getElementById('orderList').innerHTML = '';
            
            fetch(`http://localhost:8080/api/orders?page=${page-1}&size=${pageSize}`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('ordersLoading').style.display = 'none';
                    console.log('订单数据:', data); // 调试用，查看返回的数据结构
                    
                    // 处理不同的返回格式
                    let content = data;
                    let totalPages = 1;
                    
                    // 如果返回的是分页对象
                    if (data.content && Array.isArray(data.content)) {
                        content = data.content;
                        totalPages = data.totalPages || Math.ceil(data.totalElements / pageSize) || 1;
                    } else if (Array.isArray(data)) {
                        // 如果返回的是数组，手动计算分页
                        content = data.slice((page-1) * pageSize, page * pageSize);
                        totalPages = Math.ceil(data.length / pageSize);
                    }
                    
                    renderOrders(content);
                    renderOrderPagination(totalPages, page);
                })
                .catch(error => {
                    console.error('获取订单数据失败:', error);
                    document.getElementById('ordersLoading').style.display = 'none';
                    document.getElementById('orderList').innerHTML = '<tr><td colspan="7" class="text-center">加载订单数据失败，请刷新重试</td></tr>';
                    
                    // 如果接口不可用，使用示例数据
                    const demoOrders = [
                        {orderId: '20240501001', companyId: 'C001', orderType: '招标', productName: '水泥', orderTime: '2024-05-01T01:15:00.000+00:00', amount: 1000, status: '已完成'},
                        {orderId: '20240502001', companyId: 'C002', orderType: '投标', productName: '钢材', orderTime: '2024-05-02T01:15:00.000+00:00', amount: 2000, status: '进行中'},
                        {orderId: '20240503001', companyId: 'C003', orderType: '招标', productName: '沙石', orderTime: '2024-05-03T01:15:00.000+00:00', amount: 1500, status: '待审核'}
                    ];
                    
                    // 手动分页示例数据
                    const paginatedDemoOrders = demoOrders.slice((page-1) * pageSize, page * pageSize);
                    renderOrders(paginatedDemoOrders);
                    renderOrderPagination(Math.ceil(demoOrders.length / pageSize), page);
                });
        }
        
        // 渲染订单列表
        function renderOrders(orders) {
            const orderList = document.getElementById('orderList');
            orderList.innerHTML = '';
            
            if (orders.length === 0) {
                orderList.innerHTML = '<tr><td colspan="7" class="text-center">暂无订单数据</td></tr>';
                return;
            }
            
            orders.forEach(order => {
                const tr = document.createElement('tr');
                let statusClass = '';
                let statusText = order.status || '未知';
                
                if (statusText === '已完成') {
                    statusClass = 'status-badge status-on';
                } else if (statusText === '待付款' || statusText === '待审核') {
                    statusClass = 'status-badge status-off';
                } else {
                    statusClass = 'status-badge';
                }
                
                // 确保所有字段都有默认值，防止undefined显示在页面上
                const orderId = order.orderId || '未知';
                const orderType = order.orderType || '未知';
                const productName = order.productName || '未知';
                const orderTime = order.orderTime || '未知';
                const amount = order.amount || 0;
                
                // 格式化日期时间
                let formattedDate = orderTime;
                try {
                    if (orderTime.includes('T')) {
                        const date = new Date(orderTime);
                        formattedDate = date.toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit'
                        });
                    }
                } catch (e) {
                    console.error('日期格式化失败:', e);
                }
                
                tr.innerHTML = `
                    <td>${orderId}</td>
                    <td>${orderType}</td>
                    <td>${productName}</td>
                    <td>${formattedDate}</td>
                    <td>¥${typeof amount === 'number' ? amount.toFixed(2) : amount}</td>
                    <td><span class="${statusClass}">${statusText}</span></td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="viewOrderDetail('${orderId}', '${order.companyId}')">
                            <i class="bi bi-eye"></i> 查看
                        </button>
                    </td>
                `;
                orderList.appendChild(tr);
            });
        }
        
        // 渲染订单分页
        function renderOrderPagination(totalPages, currentPage) {
            const paginationElement = document.getElementById('orderPagination');
            if (!paginationElement) {
                console.error('找不到订单分页容器元素');
                return;
            }
            
            paginationElement.innerHTML = '';
            
            if (totalPages <= 1) {
                return; // 如果只有一页，不显示分页控件
            }
            
            const ul = document.createElement('ul');
            ul.className = 'pagination justify-content-center';
            
            // 上一页按钮
            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
            const prevLink = document.createElement('a');
            prevLink.className = 'page-link';
            prevLink.href = '#';
            prevLink.innerHTML = '&laquo;';
            prevLink.addEventListener('click', (e) => {
                e.preventDefault();
                if (currentPage > 1) loadOrders(currentPage - 1);
            });
            prevLi.appendChild(prevLink);
            ul.appendChild(prevLi);
            
            // 页码按钮 - 优化显示逻辑
            const maxPagesToShow = 5; // 最多显示的页码数
            let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
            let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
            
            // 调整起始页，确保显示指定数量的页码
            if (endPage - startPage + 1 < maxPagesToShow) {
                startPage = Math.max(1, endPage - maxPagesToShow + 1);
            }
            
            // 显示第一页
            if (startPage > 1) {
                const firstLi = document.createElement('li');
                firstLi.className = 'page-item';
                const firstLink = document.createElement('a');
                firstLink.className = 'page-link';
                firstLink.href = '#';
                firstLink.textContent = '1';
                firstLink.addEventListener('click', (e) => {
                    e.preventDefault();
                    loadOrders(1);
                });
                firstLi.appendChild(firstLink);
                ul.appendChild(firstLi);
                
                // 如果起始页不是第2页，显示省略号
                if (startPage > 2) {
                    const ellipsisLi = document.createElement('li');
                    ellipsisLi.className = 'page-item disabled';
                    const ellipsisSpan = document.createElement('span');
                    ellipsisSpan.className = 'page-link';
                    ellipsisSpan.innerHTML = '&hellip;';
                    ellipsisLi.appendChild(ellipsisSpan);
                    ul.appendChild(ellipsisLi);
                }
            }
            
            // 显示中间的页码
            for (let i = startPage; i <= endPage; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                const link = document.createElement('a');
                link.className = 'page-link';
                link.href = '#';
                link.textContent = i;
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    loadOrders(i);
                });
                li.appendChild(link);
                ul.appendChild(li);
            }
            
            // 显示最后一页
            if (endPage < totalPages) {
                // 如果结束页不是倒数第2页，显示省略号
                if (endPage < totalPages - 1) {
                    const ellipsisLi = document.createElement('li');
                    ellipsisLi.className = 'page-item disabled';
                    const ellipsisSpan = document.createElement('span');
                    ellipsisSpan.className = 'page-link';
                    ellipsisSpan.innerHTML = '&hellip;';
                    ellipsisLi.appendChild(ellipsisSpan);
                    ul.appendChild(ellipsisLi);
                }
                
                const lastLi = document.createElement('li');
                lastLi.className = 'page-item';
                const lastLink = document.createElement('a');
                lastLink.className = 'page-link';
                lastLink.href = '#';
                lastLink.textContent = totalPages;
                lastLink.addEventListener('click', (e) => {
                    e.preventDefault();
                    loadOrders(totalPages);
                });
                lastLi.appendChild(lastLink);
                ul.appendChild(lastLi);
            }
            
            // 下一页按钮
            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
            const nextLink = document.createElement('a');
            nextLink.className = 'page-link';
            nextLink.href = '#';
            nextLink.innerHTML = '&raquo;';
            nextLink.addEventListener('click', (e) => {
                e.preventDefault();
                if (currentPage < totalPages) loadOrders(currentPage + 1);
            });
            nextLi.appendChild(nextLink);
            ul.appendChild(nextLi);
            
            paginationElement.appendChild(ul);
            console.log('订单分页已渲染，总页数:', totalPages, '当前页:', currentPage);
        }
        
        // 查看订单详情
        window.viewOrderDetail = function(orderId, companyId) {
            // 获取订单详情
            let orderDetail = null;
            let companyDetail = null;
            
            // 获取公司信息
            fetch(`http://localhost:8080/api/companies/${companyId}`)
                .then(response => response.json())
                .then(companyData => {
                    companyDetail = companyData;
                    
                    // 获取该公司的所有订单
                    return fetch(`http://localhost:8080/api/orders/company/${companyId}`);
                })
                .then(response => response.json())
                .then(ordersData => {
                    // 找到特定订单
                    orderDetail = ordersData.find(order => order.orderId === orderId);
                    
                    if (orderDetail && companyDetail) {
                        // 格式化日期时间
                        let formattedDate = orderDetail.orderTime;
                        try {
                            if (orderDetail.orderTime.includes('T')) {
                                const date = new Date(orderDetail.orderTime);
                                formattedDate = date.toLocaleString('zh-CN', {
                                    year: 'numeric',
                                    month: '2-digit',
                                    day: '2-digit',
                                    hour: '2-digit',
                                    minute: '2-digit'
                                });
                            }
                        } catch (e) {
                            console.error('日期格式化失败:', e);
                        }
                        
                        const detailInfo = `
                            订单号: ${orderDetail.orderId}
                            订单类型: ${orderDetail.orderType}
                            商品名称: ${orderDetail.productName}
                            下单时间: ${formattedDate}
                            金额: ¥${typeof orderDetail.amount === 'number' ? orderDetail.amount.toFixed(2) : orderDetail.amount}
                            状态: ${orderDetail.status}
                            
                            公司信息:
                            公司名称: ${companyDetail.companyName}
                            法人代表: ${companyDetail.legalPerson}
                            联系电话: ${companyDetail.phone}
                            电子邮箱: ${companyDetail.email}
                        `;
                        alert(detailInfo);
                    } else {
                        alert('未找到订单详情或公司信息');
                    }
                })
                .catch(error => {
                    console.error('获取详情失败:', error);
                    alert('获取详情失败，请稍后重试');
                });
        }
        
        // 系统设置保存
        document.getElementById('saveSettings').addEventListener('click', function() {
            const systemName = document.getElementById('systemName').value;
            const adminEmail = document.getElementById('adminEmail').value;
            
            if (!systemName || !adminEmail) {
                alert('请填写完整信息');
                return;
            }
            
            // 实际应用中应该调用保存设置接口
            alert('设置保存成功');
        });
        
        // 侧边栏菜单点击切换内容
        document.querySelectorAll('.admin-menu li').forEach(item => {
            if (item.id === 'logoutBtn') {
                item.addEventListener('click', function() {
                    if (confirm('确定要退出系统吗？')) {
                        // 清除存储的秘钥
                        sessionStorage.removeItem('secretKey');
                        // 跳转到登录页
                        window.location.href = 'login.html';
                    }
                });
                return;
            }
            
            item.addEventListener('click', function() {
                const sectionId = this.getAttribute('data-section');
                if (!sectionId) return;
                
                // 更新菜单激活状态
                document.querySelectorAll('.admin-menu li').forEach(li => li.classList.remove('active'));
                this.classList.add('active');
                
                // 更新内容区标题
                document.getElementById('contentTitle').textContent = this.textContent.trim();
                
                // 切换内容区域显示
                document.querySelectorAll('.content-section').forEach(section => {
                    section.classList.remove('active');
                });
                document.getElementById(sectionId).classList.add('active');
                
                // 根据选择的内容加载数据
                if (sectionId === 'users') {
                    loadUsers();
                } else if (sectionId === 'orders') {
                    loadOrders();
                }
            });
        });
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            if (!checkLogin()) return;
            
            // 初始化TCP服务状态
            checkTcpStatus();
        });
    </script>
</body>
</html>